package com.itbuka.goods.listener;

import com.alibaba.fastjson.JSONObject;

import com.itbuka.goods.config.RabbitMqConfig;
import com.itbuka.goods.service.GoodsProductDetailsService;
import com.itbuka.order.domain.Order;
import com.itbuka.order.domain.Task;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class OrderListener {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodsProductDetailsService productDetailsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitMqConfig.ORDER_QUEUE)
    public void reduceInventory(String message) {
        Task task = JSONObject.parseObject(message, Task.class);
        //判断redis中是否有消息(根据taskId)
        Object o = redisTemplate.opsForValue().get(task.getId());
        if (o != null) {
            //有的话说明消息重复，直接返回不处理
            return;
        }
        //redis中没有消息，把taskid存入到redis中
        redisTemplate.opsForValue().set(task.getId(), task.getId(), 5, TimeUnit.MINUTES);
        //业务处理（减库存）
        Order order = JSONObject.parseObject(task.getRequestBody(), Order.class);
        //减库存
        Integer i = productDetailsService.reduceStock(order.getProductId(), order.getNum());
        if (i != 1) {
            //库存不足，发送消息给订单服务，通知订单服务，库存不足
            rabbitTemplate.convertAndSend(RabbitMqConfig.ORDER_EXCHANGE, RabbitMqConfig.ORDER_FAIL_QUEUE, order.getId());
        }
        //发消息告诉order服务删除task表中数据
        rabbitTemplate.convertAndSend(RabbitMqConfig.TASK_EXCHANGE, RabbitMqConfig.TASK_QUEUE, task.getId());
    }

    @RabbitListener(queues = RabbitMqConfig.ADD_QUEUE)
    public void addReducedInventory(String message){
        //格式转换
        Order order = JSONObject.parseObject(message, Order.class);
        //加库存
        Integer i = productDetailsService.reduceStock(order.getProductId(), -order.getNum());
        if(i != 1){
            throw new RuntimeException("加库存失败");
        }
    }
}
